<template>
  <div>
    <!-- <dialog-comp v-if="showDialog" :v-show-dialog.sync="showDialog" @dialogClose="dialogClose" ref="dialog"></dialog-comp> -->
    <modify-dialog-comp
      v-if="showDialogModify"
      :show-child-dialog.sync="showDialogModify"
      ref="dialogmodify"
      @modifyFlush="flushTable"
    ></modify-dialog-comp>
    <add-dialog-comp
      v-if="showDialogAdd"
      :show-child-dialog.sync="showDialogAdd"
      ref="dialogadd"
      @addFlush="flushTable"
    ></add-dialog-comp>
    <t-form
      ref="form"
      :data="formData"
      :label-width="80"
      colon
      @reset="onReset"
      @submit="onSubmit"
      :style="{ marginBottom: '8px' }"
    >
      <t-row style="margin-top: 20px">
        <t-col :span="10">
          <t-row :gutter="[16, 24]">
            <t-col :flex="1">
              <t-form-item label="任务名称" name="task_name">
                <t-input
                  v-model="formData.task_name"
                  class="form-item-content"
                  type="search"
                  placeholder="请输入任务名称"
                  :style="{ minWidth: '134px' }"
                />
              </t-form-item>
            </t-col>
            <t-col :flex="1">
              <t-form-item label="测试计划" name="testplan_name">
                <t-input
                  v-model="formData.testplan_name"
                  class="form-item-content"
                  type="search"
                  placeholder="请输入测试计划名称"
                  :style="{ minWidth: '134px' }"
                />
              </t-form-item>
            </t-col>
            <t-col :flex="1">
              <t-form-item label="链名称" name="chain_name">
                <t-input
                  v-model="formData.chain_name"
                  class="form-item-content"
                  type="search"
                  placeholder="请输入链名称"
                  :style="{ minWidth: '134px' }"
                />
              </t-form-item>
            </t-col>
            <t-col :flex="1">
              <t-form-item label="创建人" name="user">
                <t-select
                  v-model="formData.create_user"
                  class="form-item-content"
                  placeholder="请选择标签"
                  :options="userList"
                  :keys="{ label: 'real_name', value: 'username' }"
                  multiple
                  :minCollapsedNum="3"
                  @change="handleChangeCreateUser"
                  id="user"
                  :style="{ minWidth: '134px' }"
                />
              </t-form-item>
            </t-col>
          </t-row>
        </t-col>

        <t-col :span="2" class="operation-container">
          <t-button theme="primary" type="submit" :style="{ marginLeft: '8px' }">查询</t-button>
          <t-button type="reset" variant="base" theme="default">重置</t-button>
        </t-col>
      </t-row>
      <t-row>
        <t-col :span="1.5" class="operation-ad-container">
          <t-button @click="handleCreatTask" theme="primary" :style="{ marginRight: '8px' }"> 创建任务 </t-button>
          <t-button
            @click="handleCompare"
            theme="primary"
            :style="{ marginRight: '8px' }"
            :disabled="selectedRowKeys.length < 2"
          >
            性能比对
          </t-button>
          <t-button @click="handleDeleteTask" variant="base" theme="default" :disabled="!selectedRowKeys.length">
            删除任务
          </t-button>
          <p v-if="!!selectedRowKeys.length" class="selected-count">已选{{ selectedRowKeys.length }}项</p>
        </t-col>
      </t-row>
    </t-form>
    <div class="table-container">
      <t-table
        :data="data"
        :columns="columns"
        rowKey="id"
        :verticalAlign="verticalAlign"
        :hover="hover"
        :pagination="pagination"
        :selected-row-keys="selectedRowKeys"
        @page-change="rehandlePageChange"
        @change="rehandleChange"
        @select-change="rehandleSelectChange"
        :loading="dataLoading"
        :headerAffixedTop="true"
        :headerAffixProps="{ offsetTop, container: getContainer }"
      >
        <template #status="row">
          <p class="status" :class="['', 'warning', 'unhealth'][row.con_state]">
            {{ ['健康', '警告', '异常'][row.con_state] }}
          </p>
        </template>
        <template #op="slotProps">
          <a class="t-button-link" @click="handleClickModify(slotProps)">编辑</a>
          <a class="t-button-link" @click="handleClickDelete(slotProps)">删除</a>
        </template>
      </t-table>

      <t-dialog
        header="确认删除当前所选任务？"
        :body="confirmBody"
        :visible.sync="confirmVisible"
        @confirm="onConfirmDelete"
        :onCancel="onCancel"
        @deleteFlush="flushTable"
      >
      </t-dialog>
    </div>
  </div>
</template>
<script lang="jsx">
import Vue from 'vue';
import { prefix } from '@/config/global';
// import Trend from '@/components/trend/index.vue';
import modifyDialogComp from './ModifyDialogComp.vue';
import addDialogComp from './AddDialogComp.vue';
// import { ErrorCircleFilledIcon, CheckCircleFilledIcon, CloseCircleFilledIcon} from 'tdesign-icons-vue';
import { getUserList } from '@/api/requestApi';
import { TASK_LIST } from '@/service/service-detail';

const INITIAL_FORM_DATA = {
  task_name: '',
  testplan_name: '',
  chain_name: '',
  create_user: '',
};

export default {
  name: 'list-table',

  components: {
    modifyDialogComp,
    addDialogComp,
  },
  inject: ['reload'],
  data() {
    return {
      prefix,
      userList: [],
      formData: { ...INITIAL_FORM_DATA },
      data: [],
      selectedRowKeys: [],
      dataLoading: false,
      value: 'first',
      columns: [
        { colKey: 'row-select', type: 'multiple', width: 64, fixed: 'left' },
        {
          title: 'ID',
          fixed: 'left',
          width: 50,
          align: 'left',
          ellipsis: true,
          colKey: 'id',
        },
        {
          title: '任务名称',
          width: 100,
          ellipsis: true,
          colKey: 'task_name',
        },
        {
          title: '链名称',
          width: 50,
          ellipsis: true,
          colKey: 'chain_name',
        },
        {
          title: '测试计划',
          width: 80,
          ellipsis: true,
          colKey: 'testplan_name',
        },
        {
          title: '代理中心',
          width: 80,
          ellipsis: true,
          colKey: 'agent_name',
        },
        {
          title: '注册服务',
          width: 80,
          ellipsis: true,
          colKey: 'service',
        },
        {
          title: '状态',
          colKey: 'agent_status',
          align: 'left',
          width: 50,
        },
        {
          title: '开始时间',
          width: 100,
          ellipsis: true,
          colKey: 'start_time',
        },
        {
          title: '结束时间',
          width: 100,
          ellipsis: true,
          colKey: 'finish_time',
        },
        {
          align: 'left',
          fixed: 'right',
          width: 100,
          colKey: 'op',
          title: '操作',
        },
      ],
      rowKey: 'index',
      tableLayout: 'auto',
      verticalAlign: 'top',
      showDialogModify: false, // 控制弹窗的现实与隐藏
      showDialogAdd: false, // 控制弹窗的现实与隐藏
      bordered: true,
      hover: true,
      rowClassName: (rowKey) => `${rowKey}-class`,
      // 与pagination对齐
      pagination: {
        defaultPageSize: 20,
        total: 100,
        defaultCurrent: 1,
      },
      confirmVisible: false,
      deleteIdx: -1,
      deleteChainName: '',
    };
  },
  computed: {
    confirmBody() {
      if (this.deleteIdx > -1) {
        return '任务将被删除，删除后无法恢复';
      }
      return '批量删除后将无法恢复';
    },
    offsetTop() {
      return this.$store.state.setting.isUseTabsRouter ? 48 : 0;
    },
  },
  mounted() {
    this.data = TASK_LIST;
    this.getUserList();
  },
  methods: {
    getContainer() {
      return document.querySelector('.tdesign-starter-layout');
    },
    onReset() {
      this.formData.chain_name = '';
      this.formData.task_name = '';
      this.formData.testplan_name = '';
      this.formData.create_user = '';
    },
    onSubmit() {},
    rehandlePageChange(curr, pageInfo) {
      console.log('分页变化', curr, pageInfo);
    },
    rehandleChange(changeParams, triggerAndData) {
      console.log('统一Change', changeParams, triggerAndData);
    },
    rehandleSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys;
      console.log(selectedRowKeys);
    },

    addOrUpdateRefresh() {
      console.log('text, row');
    },
    handleClickModify(slotProps) {
      this.showDialogModify = true;
      this.$nextTick(() => {
        // 调用的是d子组件里面的init方法传递行数据
        this.$refs.dialogmodify.init(slotProps.row);
      });
    },
    // 关闭弹窗组件
    dialogClose() {
      this.showDialogModify = true;
    },
    handleCreatTask() {
      this.showDialogAdd = true;
    },
    // 性能比对
    handleCompare() {
      this.$router.push('/test/compare');
    },

    handleClickDelete(slotProps) {
      this.deleteIdx = slotProps.row.id;
      this.deleteChainName = slotProps.row.name;
      console.log('打印下单选', this.deleteIdx, slotProps);
      this.confirmVisible = true;
    },
    handleDeleteTask() {
      const selectedIdx = this.selectedRowKeys;
      // console.log("打印下多选",selectedIdx)
      this.confirmVisible = true;
    },
    onConfirmDelete() {
      // 真实业务请发起请求
      let ids = [];
      const reqParam = { ids: [], param: {}, op_type: '' };
      this.confirmVisible = false;
      // console.log("打印下单选deleteIdx",this.deleteIdx)
      if (this.deleteIdx > -1) {
        ids.push(this.deleteIdx);
        // console.log("打印下单选ids",ids)
      } else {
        ids = Array.from(Object.values(this.selectedRowKeys), (x) => x);
        // ids = Object.values(this.selectedRowKeys)
        // console.log("打印下多选ids",ids)
      }
      this.ids = ids.map(String);
      reqParam.op_type = 0;
      reqParam.ids = this.ids;
      // console.log("提交的表单内容", reqParam);
      // if (ids.length > 0) {
      //   operateChainConn(reqParam)
      //     .then((res) => {
      //       if (res.data.code === "000") {
      //         this.$message.success('链连接删除成功');
      //       } else {
      //         this.$message.error(res.data.msg)
      //       }
      //     })
      //     .catch((e) => {
      //       this.$message.error('系统异常');
      //       console.log(e);
      //     })
      //     .finally(() => {
      //       this.dataLoading = false;
      //     });
      // }
      this.flushTable();
      this.resetIdx();
    },
    // 获取创建人
    getUserList() {
      getUserList()
        .then((res) => {
          if (res.data.code === '000') {
            const list = res.data.data;
            this.userList = list;
          }
        })
        .catch((e) => {
          console.log(e);
        })
        .finally(() => {
          this.dataLoading = false;
        });
    },
    handleChangeCreateUser(...args) {
      console.log('change', ...args);
    },
    onCancel() {
      this.resetIdx();
    },
    resetIdx() {
      this.deleteIdx = -1;
    },
    closeConn() {
      this.chainConn = false;
    },
    closeLog() {
      this.chainConnLog = false;
    },
    // sleep
    sleep(ms) {
      return new Promise((resolve) => setTimeout(resolve, ms));
    },
    async flushTable() {
      await this.sleep(1000);
      this.reload();
    },
    // 处理字典
    // mapData(data) {
    //   const mappedData = { ...data };
    //   const sexMap = { '1': '男', '2': '女' };
    //   const typeMap = { '1': '类型1', '2': '类型2', '3': '类型3' };
    //   mappedData.sex = sexMap[data.sex];
    //   mappedData.type = typeMap[data.type];

    //   return mappedData;
    // }
  },
};
</script>

<style lang="less" scoped>
@import '@/style/variables.less';

.form-item-content {
  width: 50%;
}

.selected-count {
  display: inline-block;
  margin-left: var(--td-comp-margin-s);
  color: var(--td-text-color-secondary);
}
.operation-container {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.operation-ad-container {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin: 20px;
}
</style>
